package com.jy.api.service.impl;import com.jy.api.dao.*;import com.jy.api.domain.*;import com.jy.api.exception.MyException;import com.jy.api.payRes.CountStoreBillRes;import com.jy.api.service.MemberService;import com.jy.api.service.OrderService;import com.jy.api.signUpReq.AddMatchOrderItemParams;import com.jy.api.signUpReq.GetAdminOrderRes;import com.jy.api.signUpReq.admin.MemberChargeItemRes;import com.jy.api.signUpReq.admin.RemoveZeroReq;import com.jy.api.signUpReq.pos.EmpCashRes;import com.jy.api.signUpReq.pos.OrderItemSignUpReq;import com.jy.api.util.Result;import com.jy.api.util.*;import com.jy.api.util.builder.ThreadArgumentsBuilder;import com.jy.api.vo.admin.store.StoreVo;import com.jy.api.vo.member.MemberVo;import com.jy.api.vo.pos.order.OrderInfoVo;import com.jy.api.vo.pos.order.OrderVo;import com.jy.api.vo.web.WebOrderVo;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.BeanUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.lang.reflect.InvocationTargetException;import java.text.NumberFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.*;import java.util.stream.Collectors;@Slf4j@Servicepublic class OrderServiceImpl implements OrderService {    @Autowired    OrderDao orderDao;    @Autowired    PaymentDao paymentDao;    @Autowired    MemberService memberService;    @Autowired    MemberDao memberDao;    @Autowired    ProductDao productDao;    @Autowired    StoreDao storeDao;    @Autowired    StockTransactionDao stockTransactionDao;    @Autowired    EmployeeDao employeeDao;    @Autowired    ComponentUtil componentUtil;    private JdbcTemplate jdbc;    @Autowired    private CouponInstanceDao couponInstanceDao;    @Autowired    private CouponDao couponDao;    @Autowired    private WorkShiftDao shiftDao;    @Autowired    private RedisSyncLocker redisSyncLocker;    @Autowired    private StorePayDao storePayDao;    @Autowired    private DiscountPromotionDao discountPromotionDao;    @Autowired    private DiscountPromotionProductDao discountPromotionProductDao;    @Autowired    private OrderItemDao orderItemDao;    @Autowired    private DiscountOrderItemDao discountOrderItemDao;    @Autowired    private OrderItemExtraDao orderItemExtraDao;    @Autowired    private StoreNumCountDao storeNumCountDao;    @Autowired    private NumDao numDao;    @Autowired    private StoreNumDayCountDao storeNumDayCountDao;    @Autowired    private MakeOrderItemDao makeOrderItemDao;    @Autowired    private LeaseProductOrderDao leaseProductOrderDao;    @Override    @Transactional    public OrderVo addOrderItem(Order order, Product product, OrderItemSignUpReq orderItemSignUpReq) {        log.info("订单号{}, 操作{}, 添加商品{}", order.getId(), "添加商品", product);        if (order.getItems().size() == 0) {            order.setCreateTime(new Date());        }        DiscountPromotionProduct promotionProduct = discountPromotionProductDao.findByProductIdAndPromotionType(product.getId(), PromotionType.ing);        List<OrderItem> orderItems = orderItemDao.findByOrderIdAndProductId(order.getId(), product.getId());        OrderItem orderItem = null;        if (orderItems.size() > 0) {            int index = Order.checkSpec(orderItems, orderItemSignUpReq);            if (index > -1) {                orderItem = orderItems.get(index);            }        }        if (promotionProduct != null) {            log.info("订单号{}, 操作{}, 操作前订单金额{}, 操作前折扣金额{}", order.getId(), "添加订单进入第二份商品折扣", order.getAmount(), order.getDiscount());            List<DiscountOrderItem> items = discountOrderItemDao.findByOrderIdAndProductId(order.getId(), product.getId());            DiscountOrderItem item = null;            if (items.size() > 0) {                int index = Order.checkDiscountSpec(items, orderItemSignUpReq);                if (index > -1) {                    item = items.get(index);                }            }            DiscountPromotion discountPromotion = discountPromotionDao.findOne(promotionProduct.getPromotionId());            boolean status = order.addDiscount(product, orderItemSignUpReq, orderItem, discountPromotion, promotionProduct);            log.info("订单号{}, 操作{}, 操作后订单金额{}, 操作后折扣金额{},操作内容{}", order.getStoreId(), order.getId(), "添加订单进入第二份商品折扣", order.getAmount(), order.getDiscount());            if (status) {                if (item != null) {                    item.setQty(orderItem.getQuantity() / 2);                } else {                    item = new DiscountOrderItem();                    item.setQty(orderItem.getQuantity() / 2);                    item.setProductName(product.getName());                    item.setOrderItem(orderItem);                    item.setOrderId(order.getId());                    item.setProductId(product.getId());                    item.setPromotionId(discountPromotion.getId());                    item.setOrderId(order.getId());                    item.setSpecs(orderItemSignUpReq.getSpecs());                }                discountOrderItemDao.save(item);            }        } else {            Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabledIsTrue(order.getStoreId(), order.getCreatorId());            log.info("订单号{}, 操作{}, 操作前订单金额{}, 操作前折扣金额{}", order.getId(), "添加订单", order.getAmount(), order.getDiscount());            order.addClerkItem(product, orderItemSignUpReq, product.getCommissions(), employee);            log.info("订单号{}, 操作{}, 操作后订单金额{}, 操作后折扣金额{}", order.getId(), "添加订单", order.getAmount(), order.getDiscount());        }        NumberFormat nf = NumberFormat.getNumberInstance();        nf.setMaximumFractionDigits(2);        nf.setGroupingUsed(false);        order.setAmount(Double.valueOf(nf.format(order.getAmount())));        log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "添加订单详情结束", "添加订单详情" + order);        OrderVo orderVo = orderVoCouponInstance(order);        for (OrderVo.OrderItemDto item : orderVo.getItems()) {            if (item.getProductId().equals(product.getId()) && null != product.getProductSpecs()) {                item.setProductSpecs(product.getProductSpecs());            }        }        return orderVo;    }    @Override    @Transactional    public void saveOrder(Order order) {        orderDao.save(order);    }    @Override    @Transactional    public void deleteOrder(Order order, Store store) throws Exception {        order.setStatus(OrderStatus.CANCELED);        orderDao.save(order);    }    @Override    public Map<String, Object> getCharge(String storeId, String type, String begin, String end, String time, String mobile, Pageable pageable) {        Date startDate = null;        Date endDate = null;        Page<Order> orders;        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));        Map<String, Object> map = new HashMap<>();        List<String> memberIds = new ArrayList<>();        List<MemberChargeItemRes> res = new ArrayList<>();        try {            if (StringUtils.equals(type, "MONTH")) {                startDate = MyDateUtils.getMinMonthDate(time);                endDate = MyDateUtils.getMaxMonthDate(time);            } else {                startDate = simpleDateFormat.parse(begin);                endDate = simpleDateFormat.parse(end);            }        } catch (ParseException e) {            e.printStackTrace();        }        if (null == mobile || StringUtils.equals("", mobile)) {            orders = orderDao.findAllByStoreIdAndEnabledAndStatusAndTypeAndPaymentTimeBetweenOrderByPaymentTimeDesc(storeId, true, OrderStatus.FINISHED, OrderType.MEMBER_DEPOSIT, startDate, endDate,                    pageable);            double amount = 0.0;            double discount = 0.0;            for (Order order : orders) {                amount += order.getAmount();                discount += order.getDiscount();                memberIds.add(order.getMemberId());            }            List<Member> idIn = memberDao.findByIdIn(memberIds);            for (Member id : idIn) {                for (Order ord : orders) {                    if (id.getId().equals(ord.getMemberId())) {                        MemberChargeItemRes itemRes = new MemberChargeItemRes();                        itemRes.setAmount(ord.getAmount());                        itemRes.setDiscount(ord.getDiscount());                        itemRes.setMemberName(ord.getMemberName());                        itemRes.setPaymentTime(ord.getPaymentTime());                        itemRes.setMobile(id.getMobile());                        res.add(itemRes);                    }                }            }            map.put("amount", amount);            map.put("discount", discount);            map.put("result", new Result(200, "获取成功"));            map.put("data", res);            map.put("totalElements", orders.getTotalElements());            map.put("totalPages", orders.getTotalPages());            return map;        } else {            Member member = memberDao.findTop1ByMobileOrderByUpdateTimeDesc(mobile);            if (member == null) {                map.put("result", new Result(400, "该会员不存在"));                map.put("data", null);                return map;            }            orders = orderDao.findAllByStoreIdAndEnabledAndStatusAndMemberIdAndTypeAndPaymentTimeBetweenOrderByPaymentTimeDesc(storeId, true, OrderStatus.FINISHED, member.getId(),                    OrderType.MEMBER_DEPOSIT, startDate, endDate, pageable);            double amount = 0.0;            double discount = 0.0;            for (Order order : orders) {                amount += order.getAmount();                discount += order.getDiscount();                memberIds.add(order.getMemberId());            }            List<Member> idIn = memberDao.findByIdIn(memberIds);            for (Member id : idIn) {                for (Order ord : orders) {                    if (id.getId().equals(ord.getMemberId())) {                        MemberChargeItemRes itemRes = new MemberChargeItemRes();                        itemRes.setAmount(ord.getAmount());                        itemRes.setDiscount(ord.getDiscount());                        itemRes.setMemberName(ord.getMemberName());                        itemRes.setPaymentTime(ord.getPaymentTime());                        itemRes.setMobile(id.getMobile());                        res.add(itemRes);                    }                }            }            map.put("result", new Result(200, "获取成功"));            map.put("data", res);            map.put("totalElements", orders.getTotalElements());            map.put("totalPages", orders.getTotalPages());            map.put("amount", amount);            map.put("discount", discount);            return map;        }    }    @Override    public OrderVo addMatchOrderItem(Order order, AddMatchOrderItemParams req) throws MyException {        OrderItem item = orderItemDao.findOne(req.getOrderItemId());        if (item == null) {            throw new MyException("订单详情不存在");        }        Product masterProduct = productDao.findOne(item.getProductId());        if (masterProduct == null) {            throw new MyException("主商品不存在");        }        for (AddMatchOrderItemParams.AddMatchParams params : req.getMatchParams()) {            boolean add = false;            OrderItem masterItem = orderItemDao.findAllByMasterItemIdAndProductId(req.getOrderItemId(), params.getProductId());            Product product = productDao.findOne(params.getProductId());            if (product == null) {                throw new MyException("商品不存在");            }            double price = Math.rint(product.getSalesPrice() * params.getProductCount() * 100) / 100d;            if (masterItem == null) {                masterItem = new OrderItem(UuidUtil.getUuid(), product, params.getProductCount(), 0);                masterItem.setDirectTherma(masterProduct.isDirectThermal());                masterItem.setMasterItemId(item.getId());                add = true;            } else {                masterItem.setQuantity(masterItem.getQuantity() + params.getProductCount());            }            masterItem.setDealPrice(masterItem.getDealPrice() + price);            masterItem.setSalesPrice(masterItem.getSalesPrice() + price);            masterItem.setCostPrice(masterItem.getCostPrice() + product.getCostPrice() * params.getProductCount());            masterItem.setKitchenPrintEnabled(masterProduct.isKitchenPrintEnabled());            masterItem.setLabelEnabled(masterProduct.isLabelEnabled());            masterItem.setIpId(masterProduct.getIpId());            masterItem.setPort(masterProduct.getPort());            masterItem.setIpName(masterProduct.getIpName());            item.setHaveMatchEnabled(true);            masterItem.setIpAddress(masterProduct.getIpAddress());            if (add) {                order.getItems().add(masterItem);            }            order.setAmount(order.getAmount() + price);            order.setTotal(order.getTotal() + price);            order.setCount(order.getCount() + params.getProductCount());        }        return orderVoCouponInstance(order);    }    @Override    @Transactional    public void finishOrders(Order order) {        order.setStatus(OrderStatus.FINISHED);        orderDao.save(order);    }    @Override    @Transactional    public Order addMemberOrder(String id,                                Double amount,                                String username,                                String storeId,                                String memberId,                                ChargeRule chargeRule, String type) {        Member member = memberDao.findOne(memberId);        List<Object> objects = employeeDao.getEmployeeName(storeId, username);        String creatorName = objects.size() > 0 ? objects.get(0).toString() : "";        Order order = null;        if (chargeRule != null) {            order = new Order(id, storeId, username, creatorName,                    chargeRule.getId(), chargeRule.getName(), amount,                    chargeRule.getBonusAmount(),                    chargeRule.getBonusAmount() + chargeRule.getDepositAmount());        } else {            order = new Order(id, storeId, username, creatorName,                    null, null, amount,                    0d, 0d);        }        if (StringUtils.equals("CLERK", type)) {            order.setSource(OrderSource.EMPLOYEE);        } else {            order.setSource(OrderSource.POS);        }        order.setMemberId(memberId);        order.setMemberName(member.getName());        orderDao.save(order);        return order;    }    @Override    public List<GetAdminOrderRes> getStoreBillByOrderId(String orderId) {        Order order = orderDao.findOne(orderId);        List<OrderItem> orderItems = order.getItems();        List<GetAdminOrderRes> list = new ArrayList<>();        Member member = null;        if (null != order.getMemberId()) {            member = memberDao.findOne(order.getMemberId());        }        for (OrderItem item : orderItems) {            GetAdminOrderRes res = new GetAdminOrderRes();            res.setAmount(item.getDealPrice());            res.setProductName(item.getProductName());            res.setQty(item.getQuantity());            if (member != null) {                res.setMemberName(member.getName());                res.setMobile(member.getMobile());            }            list.add(res);        }        return list;    }    @Override    @Transactional    public OrderVo attachCouponInstanceOrder(Order order, String couponInstanceCode, Coupon coupon, String productId) {        OrderVo orderVo = new OrderVo();        if (!coupon.haveProductId(productId)) {            throw new MyException("优惠券使用失败！商品匹配错误");        }        Product product = productDao.findOne(productId);        if (product == null) {            throw new MyException("优惠券使用失败！商品信息不存在！");        }        CouponInstance instance = couponInstanceDao.findByCode(couponInstanceCode);        if (coupon.isOpenLimitEnabled()) {            long count = couponInstanceDao.countEverDayValidateCount(coupon.getId(), instance.getOwnerId(), MyDateUtils.getEarliest(new Date()), MyDateUtils.getLastest(new Date()));            if (count >= coupon.getLimitCount()) {                throw new MyException("已超出优惠券每天使用最大份数！");            }        }        double commission = 0;        double amount = 0;        for (OrderItem item : order.getItems()) {            if (item.getProductId().equals(product.getId())) {                if (coupon.getType().equals(CouponType.GET_ITEM_FREE)) {                    //140 /2  -70=0                    double v = item.getDealPrice() - product.getSalesPrice();                    if (v < 0) {                        amount = item.getDealPrice();                    } else {                        amount = product.getSalesPrice();                    }                    item.setDealPrice(v < 0 ? 0 : v);                } else {                    amount = coupon.getCouponAmount();                    if (amount > product.getSalesPrice()) {                        amount = product.getSalesPrice();                    }                    double v = item.getDealPrice() - amount;                    item.setDealPrice(v < 0 ? 0 : v);                }            }            commission += item.getCommission();        }        double couponDiscount = Math.min(order.getAmount(), amount);        order.setCouponDiscountAmount(couponDiscount);        order.setAmount(order.getAmount() - couponDiscount);        order.setDiscount(order.getDiscount() + couponDiscount);        order.setCommission(commission);        //订单相关数据处理        order.handleCoupon(product);        orderDao.save(order);        BeanUtils.copyProperties(order, orderVo);        OrderVo.CouponInstance couponInstance = new OrderVo.CouponInstance();        couponInstance.setCouponInstanceCode(couponInstanceCode);        couponInstance.setCouponName(coupon.getTitle());        couponInstance.setProductId(product.getId());        couponInstance.setProductName(product.getName());        couponInstance.setProductQuantity((short) 1);        couponInstance.setProductSalePrice((int) (product.getSalesPrice() * 100));        orderVo.getCouponInstances().add(couponInstance);        instance.setCouponAmount(amount);        instance.setOrderProductId(productId);        instance.setOrderId(order.getId());        couponInstanceDao.save(instance);        List<DiscountOrderItem> list = discountOrderItemDao.findByOrderId(order.getId());        orderVo.setDiscountOrderItem(list);        return orderVo;    }    @Override    @Transactional    public OrderVo relieveCouponInstanceOrder(Order order, String couponInstanceCode, String productId) {        OrderVo orderVo = new OrderVo();        CouponInstance couponInstance = couponInstanceDao.findByCode(couponInstanceCode);        Coupon coupon = couponDao.findOne(couponInstance.getCouponId());        Product product = productDao.findOne(productId);        if (product == null) {            throw new MyException("商品信息不存在");        }        double commission = 0;        for (OrderItem item : order.getItems()) {            if (item.getProductId().equals(productId)) {                item.setDealPrice(item.getDealPrice() + order.getCouponDiscountAmount());            }            commission += item.getCommission();        }        order.relieveCoupon(product, order.getCouponDiscountAmount(), coupon, commission);        BeanUtils.copyProperties(order, orderVo);        couponInstance.setOrderId(null);        couponInstanceDao.save(couponInstance);        List<DiscountOrderItem> list = discountOrderItemDao.findByOrderId(order.getId());        orderVo.setDiscountOrderItem(list);        saveOrder(order);        return orderVo;    }    @Override    public List<OrderVo> setOrderVoCouponInstance(List<Order> orders) {        List<OrderVo> orderVos = new LinkedList<>();        List<String> orderIds = orders.stream().map(e -> e.getId()).collect(Collectors.toList());        if (orderIds.size() > 0) {            List<Payment> payments = paymentDao.findListByOrderIdIn(orderIds);            for (Order order : orders) {                List<OrderVo.OrderItemDto> dtos = new ArrayList<>();                OrderVo orderVo = new OrderVo();                BeanUtils.copyProperties(order, orderVo);                List<Payment> payments1 = new ArrayList<>();                for (Payment payment : payments) {                    if (StringUtils.equals(order.getId(), payment.getOrderId())) {                        payments1.add(payment);                        setOrderVo(payment, orderVo);                    }                }                log.info("订单号{},保存订单内容{}", order.getId(), order);                List<String> orderItemId = order.getItems().stream().map(OrderItem::getId).collect(Collectors.toList());                List<MakeOrderItem> makeOrderItems = makeOrderItemDao.findByOrderItemIdInOrderByIdAsc(orderItemId);                List<String> makeIds = new ArrayList<>();                List<String> codes = new ArrayList<>();                List<String> tips = new ArrayList<>();                for (MakeOrderItem makeOrderItem : makeOrderItems) {                    if (null != makeOrderItem.getTips() && makeOrderItem.getTips().size() > 0) {                        tips.addAll(makeOrderItem.getTips());                    }                    OrderItem oneItem = order.getOneItem(makeOrderItem.getOrderItemId());                    if (oneItem != null) {                        codes.add(makeOrderItem.getCode() + "--" + oneItem.isLabelEnabled());                        makeIds.add(makeOrderItem.getId() + "--" + oneItem.isLabelEnabled());                    }                }                payments.removeAll(payments1);                for (OrderItem item : order.getItems()) {                    OrderVo.OrderItemDto dto = new OrderVo.OrderItemDto();                    BeanUtils.copyProperties(item, dto);                    dto.setMakeIds(makeIds);                    dto.setDeliveryName(order.getCreatorName());                    dto.setSpecs(item.getSpecs());                    dto.setCodes(codes);                    dto.setTips(tips);                    List<OrderVo.OrderItemDto.MasterItemDto> masterItemDtos = new ArrayList<>();                    if (item.isHaveMatchEnabled()) {                        List<OrderItem> masterItem = orderItemDao.findAllByMasterItemId(item.getId());                        for (OrderItem orderItem : masterItem) {                            OrderVo.OrderItemDto.MasterItemDto masterItemDto = new OrderVo.OrderItemDto.MasterItemDto();                            BeanUtils.copyProperties(orderItem, masterItemDto);                            masterItemDtos.add(masterItemDto);                        }                        dto.setMasterItemDtos(masterItemDtos);                    }                    if (StringUtils.isBlank(item.getMasterItemId())) {                        dtos.add(dto);                    }                }                if (StringUtils.isNotBlank(order.getMemberId())) {                    Member member = memberDao.findOne(order.getMemberId());                    if (member != null) {                        orderVo.setMemberMobile(member.getMobile());                    }                }                orderVo.setDeliveryName(order.getCreatorName());                orderVo.setItems(dtos);                orderVos.add(orderVo);            }        }        return orderVos;    }    @Override    public OrderVo orderVoCouponInstance(Order order) {        OrderVo orderVo = new OrderVo();        List<OrderVo.OrderItemDto> dtos = new ArrayList<>();        List<Payment> payments = paymentDao.findByOrderIdAndEnabled(order.getId(), true);        BeanUtils.copyProperties(order, orderVo);        for (Payment payment : payments) {            //如果确认为            if (StringUtils.equals(order.getId(), payment.getOrderId())) {                setOrderVo(payment, orderVo);            }        }        List<DiscountOrderItem> list = discountOrderItemDao.findByOrderId(order.getId());        orderVo.setDiscountOrderItem(list);        orderDao.save(order);        log.info("订单号{},保存订单内容{}", order.getId(), order);        List<String> orderItemId = order.getItems().stream().map(OrderItem::getId).collect(Collectors.toList());        List<MakeOrderItem> makeOrderItems = makeOrderItemDao.findByOrderItemIdInOrderByIdAsc(orderItemId);        List<String> makeIds = new ArrayList<>();        List<String> codes = new ArrayList<>();        List<String> tips = new ArrayList<>();        for (MakeOrderItem makeOrderItem : makeOrderItems) {            if (null != makeOrderItem.getTips() && makeOrderItem.getTips().size() > 0) {                tips.addAll(makeOrderItem.getTips());            }            OrderItem oneItem = order.getOneItem(makeOrderItem.getOrderItemId());            if (oneItem != null) {                codes.add(makeOrderItem.getCode() + "--" + oneItem.isLabelEnabled());                makeIds.add(makeOrderItem.getId() + "--" + oneItem.isLabelEnabled());            }        }        for (OrderItem item : order.getItems()) {            OrderVo.OrderItemDto dto = new OrderVo.OrderItemDto();            BeanUtils.copyProperties(item, dto);            dto.setMakeIds(makeIds);            dto.setSpecs(item.getSpecs());            dto.setCodes(codes);            dto.setDeliveryName(order.getCreatorName());            dto.setTips(tips);            if (null != item.getSpecs() && item.getSpecs().size() > 0) {                Product product = productDao.findOne(item.getProductId());                if (null != product.getProductSpecs()) {                    dto.setProductSpecs(product.getProductSpecs());                }            }            List<OrderVo.OrderItemDto.MasterItemDto> masterItemDtos = new ArrayList<>();            if (item.isHaveMatchEnabled()) {                List<OrderItem> masterItem = orderItemDao.findAllByMasterItemId(item.getId());                for (OrderItem orderItem : masterItem) {                    OrderVo.OrderItemDto.MasterItemDto masterItemDto = new OrderVo.OrderItemDto.MasterItemDto();                    BeanUtils.copyProperties(orderItem, masterItemDto);                    masterItemDto.setSpecs(orderItem.getSpecs());                    masterItemDtos.add(masterItemDto);                }                dto.setMasterItemDtos(masterItemDtos);            }            if (StringUtils.isBlank(item.getMasterItemId())) {                dtos.add(dto);            }        }        if (StringUtils.isNotBlank(order.getMemberId())) {            Member member = memberDao.findOne(order.getMemberId());            if (member != null) {                orderVo.setMemberMobile(member.getMobile());            }        }        orderVo.setDeliveryName(order.getCreatorName());        orderVo.setItems(dtos);        return orderVo;    }    /**     * 设置返回实体类     *     * @param payment     * @param orderVo     */    private void setOrderVo(Payment payment, OrderVo orderVo) {        //如果为优惠卷支付        if (payment.getChannel().equals(PaymentChannel.COUPON.name())) {            OrderVo.CouponInstance couponInstance = new OrderVo.CouponInstance();            BeanUtils.copyProperties(payment, couponInstance);            orderVo.getCouponInstances().add(couponInstance);        } else {            if (payment.isSuccess()) {                OrderVo.Payment payment1 = new OrderVo.Payment();                BeanUtils.copyProperties(payment, payment1);                orderVo.getPayments().add(payment1);            }        }    }    @Override    public List<com.jy.api.vo.member.OrderVo> getMemberRecord(String memberId, Pageable pageable) {        Page<Order> orders = orderDao.findByMemberIdAndStatusIn(memberId, Arrays.asList(OrderStatus.FINISHED,                OrderStatus.UNFINISHED, OrderStatus.REFUNDED), pageable);        List<com.jy.api.vo.member.OrderVo> orderVos = orders.getContent().stream().map(e ->                new com.jy.api.vo.member.OrderVo(e.getId(),                        e.getCode(), (int) Math.rint(e.getAmount() * 100),                        e.getPaymentTime(), e.getType(), e.getStatus())        ).collect(Collectors.toList());        return orderVos;    }    @Override    public List<com.jy.api.vo.member.OrderVo> getMemberRecordAndStoreId(String memberId, String storeId, Pageable pageable) {        Page<Order> orders = orderDao.findByMemberIdAndStatusInAndStoreId(memberId, Arrays.asList(OrderStatus.FINISHED,                OrderStatus.UNFINISHED, OrderStatus.REFUNDED), storeId, pageable);        List<com.jy.api.vo.member.OrderVo> orderVos = orders.getContent().stream().map(e ->                new com.jy.api.vo.member.OrderVo(e.getId(),                        e.getCode(), (int) Math.rint(e.getAmount() * 100),                        e.getPaymentTime(), e.getType(), e.getStatus())        ).collect(Collectors.toList());        return orderVos;    }    @Override    @Transactional    public void removeOrderItem(Order order, Product product, OrderItemSignUpReq orderItemSignUpReq) throws Exception {        log.info("门店{},订单{}, 订单号{}, 操作{}, 操作内容{},订单详情{}", order.getStoreId(), order, order.getId(), "移除商品开始", "移除商品" + product, order.getItems());        //true 订单无优惠卷处理  false 订单有折扣处理        OrderItem resultItem = null;        boolean deduction = true;        Payment payment = paymentDao.findByOrderIdAndProductIdAndEnabled(order.getId(), product.getId(), true);        if (payment != null) {            for (OrderItem item : order.getItems()) {                if (StringUtils.equals(product.getId(), payment.getProductId())                        && item.getQuantity() == 1) {                    payment.setEnabled(false);                    paymentDao.save(payment);                    deduction = false;                    break;                }            }        }        DiscountPromotionProduct promotionProduct = discountPromotionProductDao.findByProductIdAndPromotionType(product.getId(), PromotionType.ing);        //移除订单明细项        if (promotionProduct != null) {            DiscountPromotion discountPromotion = discountPromotionDao.findOne(promotionProduct.getPromotionId());            List<OrderItem> orderItems = orderItemDao.findByOrderIdAndProductId(order.getId(), product.getId());            int index = Order.checkSpec(orderItems, orderItemSignUpReq);            OrderItem orderItem = null;            if (index > -1) {                orderItem = orderItems.get(index);            }            List<DiscountOrderItem> items = discountOrderItemDao.findByOrderIdAndProductId(order.getId(), product.getId());            DiscountOrderItem discountOrderItem = null;            if (items.size() > 0) {                int disCountIndex = Order.checkDiscountSpec(items, orderItemSignUpReq);                if (disCountIndex > -1) {                    discountOrderItem = items.get(disCountIndex);                }            }            if (discountOrderItem != null) {                if ((orderItem.getQuantity() - orderItemSignUpReq.getProductCount()) % 2 == 0) {                    //移除的是单个.不用做特殊处理                    order.removeDiscountOrderItemOut(orderItem, orderItemSignUpReq.getProductCount(), product);                } else {                    //订单添加时间不在折扣范围内.不用做特殊处理                    if (!Order.judgeTimeIn(discountPromotion, orderItem.getAddTime())) {                        order.removeDiscountOrderItemOut(orderItem, orderItemSignUpReq.getProductCount(), product);                    } else {                        //订单添加时间在折扣范围内.做特殊处理                        order.removeDiscountOrderItemIn(orderItem, orderItemSignUpReq.getProductCount(), product, discountPromotion, promotionProduct.getDiscountCommission());                        if (discountOrderItem.getQty() - 1 == 0) {                            discountOrderItemDao.delete(discountOrderItem);                        } else {                            discountOrderItem.setQty(discountOrderItem.getQty() - 1);                            discountOrderItemDao.save(discountOrderItem);                        }                    }                }            } else {                order.removeDiscountOrderItemOut(orderItem, orderItemSignUpReq.getProductCount(), product);            }        } else {            Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabledIsTrue(order.getStoreId(), order.getCreatorId());            if (product.isDisShow() && MyDateUtils.judgeWeek(product.getWeek()) && MyDateUtils.judgeDateSize(product.getNowHours(), product.getTomorrowHour())) {                resultItem = order.removeItem(product.getId(),                        (product.getSalesPrice() * product.getDisPrice()) * orderItemSignUpReq.getProductCount(),                        orderItemSignUpReq.getProductCount(),                        orderItemSignUpReq.getProductCount() * product.getCommission(), deduction, product, employee, orderItemSignUpReq.getSpecs());            } else {                resultItem = order.removeItem(product.getId(),                        product.getSalesPrice() * orderItemSignUpReq.getProductCount(),                        orderItemSignUpReq.getProductCount(),                        orderItemSignUpReq.getProductCount() * product.getCommission(), deduction, product, employee, orderItemSignUpReq.getSpecs());            }        }        if (resultItem != null) {            if (!resultItem.isEnabled()) {                List<OrderItem> orderItems = orderItemDao.findAllByMasterItemId(resultItem.getId());                for (OrderItem item : orderItems) {                    item.setEnabled(false);                    order.setCount(order.getCount() - item.getQuantity());                    order.setAmount(order.getAmount() - item.getDealPrice());                    order.setTotal(order.getTotal() - item.getDealPrice());                }            }        }        log.info("门店{}, 订单{},订单号{}, 操作{}, 操作内容{},订单详情{}", order.getStoreId(), order, order.getId(), "移除商品结束", "移除商品" + product, order.getItems());    }    @Override    @Transactional    public OrderVo relieveMember(Order order) {        order.setMemberId(null);        order.setMemberName(null);        double amount = 0.0;        double total = 0.0;        double commission = 0.0;        double dis = 0.0;        List<Payment> payments = paymentDao.findListByOrderIdAndEnabledAndCouponInstanceCodeIsNotNull(order.getId(), true);        List<String> productIds = payments.stream().map(e -> e.getProductId()).collect(Collectors.toList());        Map<String, Product> map = productDao.findListByIdIn(productIds).stream().                collect(Collectors.toMap(Product::getId, product -> product));        for (Payment payment : payments) {            Product product = map.get(payment.getProductId());            order.relieveCoupon(product, order.getCouponDiscountAmount(), null, 0);        }        CouponInstance couponInstance = couponInstanceDao.findByOrderIdAndStauts(order.getId(), CouponInstanceStatus.NORMAL);        if (couponInstance != null) {            couponInstance.setOrderId(null);            couponInstanceDao.save(couponInstance);        }        paymentDao.delete(payments);        if (order.getMemberId() == null) {            if (order.getItems().size() > 0) {                for (OrderItem item : order.getItems()) {                    DiscountPromotionProduct promotionProduct = discountPromotionProductDao.findByProductIdAndPromotionType(item.getProductId(), PromotionType.ing);                    if (promotionProduct == null) {                        Product product = productDao.findOne(item.getProductId());                        if (product.isMemberShow() && product.isDisShow() && MyDateUtils.judgeDateSize(product.getNowHours(), product.getTomorrowHour())) {                            item.setSalesPrice(Math.rint((product.getSalesPrice() * product.getDisPrice()) * item.getQuantity() * 100) / 100d);                            item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                            item.setCommission(Math.rint(product.getDisCom() * item.getQuantity() * 100) / 100d);                            item.setDealPrice(Math.rint((product.getSalesPrice() * product.getDisPrice()) * item.getQuantity() * 100) / 100d);                            commission += item.getCommission();                            //总价格                            total += product.getSalesPrice() * item.getQuantity();                            //折扣后的价格                            amount += item.getSalesPrice();                        } else if (product.isMemberShow()) {                            item.setSalesPrice(Math.rint(product.getSalesPrice() * item.getQuantity() * 100) / 100d);                            item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                            item.setCommission(Math.rint(product.getCommission() * item.getQuantity() * 100) / 100d);                            item.setDealPrice(Math.rint(product.getSalesPrice() * item.getQuantity() * 100) / 100d);                            commission += item.getCommission();                            //总价格                            total += product.getSalesPrice() * item.getQuantity();                            //折扣后的价格                            amount += item.getSalesPrice();                        } else {                            commission += item.getCommission();                            //总价格                            total += product.getSalesPrice() * item.getQuantity();                            //折扣后的价格                            amount += item.getSalesPrice();                        }                    } else {                        commission += item.getCommission();                        //总价格                        total += item.getSalesPrice();                        //折扣后的价格                        amount += item.getDealPrice();                    }                    dis = total - amount;                    order.setAmount(amount);                    order.setTotal(total);                    order.setDiscount(dis);                    log.info("订单号{},操作{},订单总金额{},订单应付金额{},折扣金额{}", order.getId(), "relieveMember", order.getTotal(), amount, order.getDiscount());                    order.setCommission(commission);                }            }        }        orderDao.save(order);        return orderVoCouponInstance(order);    }    @Override    public List<OrderVo> getOrderUntreated(String storeId, WorkShift shift) {        List<Order> orders = orderDao.findListByStoreIdAndEnabledAndStatusInAndAddTimeGreaterThanEqualOrderByUpdateTimeDesc(storeId, true, Arrays.asList(OrderStatus.NOTSURE), shift.getBeginTime());        return setOrderVoCouponInstance(orders);    }    @Override    public WebOrderVo getMemberOrderList(String memberId, Pageable pageable) {        Page<Order> orders = orderDao.findByMemberIdAndStatusIn(memberId, Arrays.asList(OrderStatus.FINISHED,                OrderStatus.UNFINISHED, OrderStatus.REFUNDED, OrderStatus.NOTSURE, OrderStatus.FAIL), pageable);        WebOrderVo webOrderVo = new WebOrderVo(orders.getTotalPages(), orders.getTotalElements());        webOrderVo.setOrderVos(setOrderVoCouponInstance(orders.getContent()));        return webOrderVo;    }    @Override    @Transactional    public void createWebOrder(Store store, String orderId, String memberId) {        Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabled(store.getId(), store.getUsername(), true);        if (employee == null) {            throw new MyException("店员信息有误");        }        Order order = new Order(orderId, store.getId(), store.getUsername(),                employee.getName(), OrderSource.WEB, new Date());        order.setCode(Md5Util.encrypt16(orderId));        if (StringUtils.isNotBlank(memberId)) {            Member member = memberDao.findOne(memberId);            if (member == null) {                throw new MyException("会员信息有误！");            }            order.setMemberId(member.getId());            order.setMemberName(member.getName());        }        orderDao.save(order);    }    @Override    @Transactional    public String orderPrePayment(Order order, Payment payment) {        order.setPayId(payment.getId());        order.setStatus(OrderStatus.NOTSURE);        orderDao.save(order);        paymentDao.save(payment);        return componentUtil.getMemberPre().replace("ORDER_ID", order.getId());    }    @Override    @Transactional    public void createOrderWechat(String orderId, String openid, String storeId) throws ParseException {        Order order = new Order(orderId, storeId, null,                "微信点单", OrderSource.WEIXIN, new Date());        MemberVo member = memberService.getMemberInfo(openid);        order.setCode(Md5Util.encrypt16(orderId));        order.setMemberId(member.getId());        order.setMemberName(member.getName());        orderDao.save(order);    }    @Override    @Transactional    public void orderNotes(Order order, String notes) {        order.setNotes(notes);        orderDao.save(order);    }    @Override    public List<OrderInfoVo> getFinishedOrders(String storeId, Date start, Pageable pageable) {        List<OrderInfoVo> infoVos = new ArrayList<>();        Page<Order> orders = orderDao.findListByStoreIdAndStatusAndEnabledAndAmountGreaterThanEqualAndCountGreaterThanEqualAndPaymentTimeGreaterThanEqualAndTypeIn(storeId,                OrderStatus.FINISHED, true, 0.0, 0, start, Arrays.asList(OrderType.SALES, OrderType.MEMBER_DEPOSIT), pageable);        for (Order order : orders) {            OrderInfoVo orderInfoVo = new OrderInfoVo();            BeanUtils.copyProperties(order, orderInfoVo);            if (order.getType() == OrderType.SALES) {                orderInfoVo.setProductInfo(getProductInfo(order.getItems()));            } else {                orderInfoVo.setProductInfo(getMemberProductInfo(order.getItems()));            }            infoVos.add(orderInfoVo);        }        return infoVos;    }    @Override    public List<OrderVo> getOrderUntreated(WorkShift shift, Pageable pageable) {        Page<Order> orders = orderDao.findListByStoreIdAndStatusInAndPaymentTimeBetween(shift.getStoreId(),                Arrays.asList(OrderStatus.FINISHED, OrderStatus.REFUNDED), shift.getBeginTime(),                shift.getEndTime() != null ? shift.getEndTime() : new Date(), pageable);        return setOrderVoCouponInstance(orders.getContent());    }    @Transactional    @Override    public void orderFaliHandle(String paymentId) throws Exception {        Payment payment = paymentDao.findOne(paymentId);        redisSyncLocker.idLock(payment.getOrderId(), (ISyncExecutor) o -> {            Order order = orderDao.findOne(payment.getOrderId());            if (StringUtils.equals(order.getPayId(), paymentId)) {                order.setStatus(OrderStatus.FAIL);                orderDao.save(order);            }            return null;        });        if (payment.getStatus() == PaymentStatus.NOTSURE) {            payment.setStatus(PaymentStatus.FAIL);            paymentDao.save(payment);        }    }    @Override    public Map<String, Object> getSalesStatics(String storeId, String typeId, String productId, Date fromDatetime, Date toDateTime) {        Map<String, Object> params = new HashMap<>();        params.put("fromDatetime", fromDatetime);        params.put("toDatetime", toDateTime);        params.put("storeId", storeId);        params.put("productId", productId);        params.put("productTypeId", typeId);        StringBuffer sqlBuf = new StringBuffer();        sqlBuf.append("SELECT COALESCE(sum(item.`sales_price` * 100), 0) as cashAmount" +                ", 0 as alipayAmount" +                ", 0 as wechatAmount" +                ", 0 as alipayCashAmount" +                ", 0 as wechatCashAmount" +                ", 0 as memberAmount" +                ", 0 as couponAmount" +                "  FROM `order` as o join `order_item` as item on o.`id`= item.`order_id`\n" +                " where o.`payment_time` between :fromDatetime and :toDatetime\n" +                "   and o.`store_id`= :storeId and o.status in('FINISHED', 'REFUNDED')" +                "   and item.`enabled` is true");        if (StringUtils.isNotEmpty(productId)) {            sqlBuf.append(" and item.product_id=:productId ");        }        if (StringUtils.isNotEmpty(typeId)) {            sqlBuf.append(" and item.product_type_id=:productTypeId ");        }        return new NamedParameterJdbcTemplate(jdbc).queryForMap(sqlBuf.toString(), params);    }    @Override    @Transactional    public void patch(String orderId, Map<String, Object> patchData) throws Exception {        // 移除一些不允许直接被更新的关键属性        patchData.remove("status");        patchData.remove("amount");        patchData.remove("discount");        patchData.remove("commission");        try {            redisSyncLocker.idLock(orderId, o -> {                Order order = orderDao.findOne(orderId);                org.apache.commons.beanutils.BeanUtils.copyProperties(order, patchData);                orderDao.save(order);                return null;            });        } catch (IllegalAccessException e) {            throw new RuntimeException(e);        } catch (InvocationTargetException e) {            throw new RuntimeException(e);        }    }    @Override    public Order findOne(String orderId) {        return orderDao.findOne(orderId);    }    @Override    public void judgeOrderItem(Order order) {        double amount = 0.0;        double total = 0.0;        double commission = 0.0;        double dis = 0.0;        if (order.getItems().size() > 0) {            for (OrderItem item : order.getItems()) {                Product product = productDao.findOne(item.getProductId());                DiscountPromotionProduct promotionProduct = discountPromotionProductDao.findByProductIdAndPromotionType(product.getId(), PromotionType.ing);                if (promotionProduct == null) {                    if (product.isMemberShow() && product.isDisShow() && MyDateUtils.judgeDateSize(product.getNowHours(), product.getTomorrowHour())) {                        item.setSalesPrice(Math.rint((product.getMemberPrice() * product.getDisPrice()) * item.getQuantity() * 100) / 100d);                        item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                        item.setCommission(Math.rint(product.getDisCom() * item.getQuantity() * 100) / 100d);                        item.setDealPrice(Math.rint((product.getMemberPrice() * product.getDisPrice()) * item.getQuantity() * 100) / 100d);                        commission += item.getCommission();                        //总价格                        total += product.getSalesPrice() * item.getQuantity();                        //折扣后的价格                        amount += item.getSalesPrice();                    } else if (product.isMemberShow()) {                        item.setSalesPrice(Math.rint(product.getMemberPrice() * item.getQuantity() * 100) / 100d);                        item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                        item.setCommission(Math.rint(product.getCommission() * item.getQuantity() * 100) / 100d);                        item.setDealPrice(Math.rint(product.getMemberPrice() * item.getQuantity() * 100) / 100d);                        commission += item.getCommission();                        //总价格                        total += product.getSalesPrice() * item.getQuantity();                        //折扣后的价格                        amount += item.getSalesPrice();                    } else if (product.isDisShow() && MyDateUtils.judgeDateSize(product.getNowHours(), product.getTomorrowHour())) {                        item.setSalesPrice(Math.rint(product.getSalesPrice() * product.getDisPrice() * item.getQuantity() * 100) / 100d);                        item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                        item.setCommission(Math.rint(product.getDisCom() * item.getQuantity() * 100) / 100d);                        item.setDealPrice(Math.rint(product.getSalesPrice() * product.getDisPrice() * item.getQuantity() * 100) / 100d);                        commission += item.getCommission();                        //总价格                        total += product.getSalesPrice() * item.getQuantity();                        //折扣后的价格                        amount += item.getSalesPrice();                    } else {                        commission += item.getCommission();                        //总价格                        total += product.getSalesPrice() * item.getQuantity();                        //折扣后的价格                        amount += item.getSalesPrice();                    }                } else {                    commission += item.getCommission();                    //总价格                    total += product.getSalesPrice() * item.getQuantity();                    //折扣后的价格                    amount += item.getDealPrice();                }                NumberFormat nf = NumberFormat.getNumberInstance();                nf.setMaximumFractionDigits(2);                nf.setGroupingUsed(false);                dis = total - amount;                order.setAmount(Double.valueOf(nf.format(amount)));                order.setTotal(total);                order.setDiscount(Double.valueOf(nf.format(dis)));                log.info("订单号{},操作{},订单总金额{},订单应付金额{},折扣金额{}", order.getId(), "judgeOrderItem", order.getTotal(), amount, order.getDiscount());                order.setCommission(commission);            }        }    }    @Override    public Order judgeWebOrderItem(Order order) {        double amount = 0.0;        double total = 0.0;        double commission = 0.0;        double dis = 0.0;        if (order.getItems().size() > 0) {            for (OrderItem item : order.getItems()) {                Product product = productDao.findOne(item.getProductId());                if (product.isMemberShow() && product.isDisShow() && MyDateUtils.judgeDateSize(product.getNowHours(), product.getTomorrowHour())) {                    item.setSalesPrice(Math.rint((product.getMemberPrice() * product.getDisPrice()) * item.getQuantity() * 100) / 100d);                    item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                    item.setCommission(Math.rint(product.getDisCom() * item.getQuantity() * 100) / 100d);                    item.setDealPrice(Math.rint((product.getMemberPrice() * product.getDisPrice()) * item.getQuantity() * 100) / 100d);                    commission += item.getCommission();                    //总价格                    total += product.getSalesPrice() * item.getQuantity();                    //折扣后的价格                    amount += item.getSalesPrice();                } else if (product.isMemberShow()) {                    item.setSalesPrice(Math.rint(product.getMemberPrice() * item.getQuantity() * 100) / 100d);                    item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                    item.setCommission(Math.rint(product.getCommission() * item.getQuantity() * 100) / 100d);                    item.setDealPrice(Math.rint(product.getMemberPrice() * item.getQuantity() * 100) / 100d);                    commission += item.getCommission();                    //总价格                    total += product.getSalesPrice() * item.getQuantity();                    //折扣后的价格                    amount += item.getSalesPrice();                } else if (product.isDisShow() && MyDateUtils.judgeDateSize(product.getNowHours(), product.getTomorrowHour())) {                    item.setSalesPrice(Math.rint(product.getSalesPrice() * product.getDisPrice() * item.getQuantity() * 100) / 100d);                    item.setCostPrice(Math.rint(product.getCostPrice() * item.getQuantity() * 100) / 100d);                    item.setCommission(Math.rint(product.getDisCom() * item.getQuantity() * 100) / 100d);                    item.setDealPrice(Math.rint(product.getSalesPrice() * product.getDisPrice() * item.getQuantity() * 100) / 100d);                    commission += item.getCommission();                    //总价格                    total += product.getSalesPrice() * item.getQuantity();                    //折扣后的价格                    amount += item.getSalesPrice();                } else {                    commission += item.getCommission();                    //总价格                    total += product.getSalesPrice() * item.getQuantity();                    //折扣后的价格                    amount += item.getSalesPrice();                }                dis = total - amount;                order.setAmount(amount);                order.setTotal(total);                order.setDiscount(dis);                log.info("订单号{},操作{},订单总金额{},订单应付金额{},折扣金额{}", order.getId(), "judgeWebOrderItem", order.getTotal(), amount, order.getDiscount());                order.setCommission(commission);            }        }        return orderDao.save(order);    }    @Override    public Map<String, Object> removeOrderByZero(RemoveZeroReq req) throws Exception {        return (Map<String, Object>) redisSyncLocker.idLock(req.getOrderId(), o -> {            Order order = orderDao.findOne(req.getOrderId());            Map<String, Object> map = new HashMap<>();            order.setRemoveZero(order.getAmount() - req.getAmount());            order.setAmount(req.getAmount());            Order returnOrder = orderDao.save(order);            List<DiscountOrderItem> list = discountOrderItemDao.findByOrderId(order.getId());            map.put("discountOrderItem", list);            map.put("result", new Result(200, "抹零成功"));            map.put("data", returnOrder);            return map;        });    }    @Override    @Transactional    public Map<String, Object> orderDiscount(RemoveZeroReq req) throws Exception {        return (Map<String, Object>) redisSyncLocker.idLock(req.getOrderId(), o -> {            Order order = orderDao.findOne(req.getOrderId());            Map<String, Object> map = new HashMap<>();            order.setDiscount(order.getDiscount() + Math.rint(((order.getAmount() - (order.getAmount() * req.getPercent())) * 100)) / 100d);            order.setAmount(Math.rint(req.getPercent() * order.getAmount() * 100) / 100d);            for (OrderItem item : order.getItems()) {                item.setDealPrice(item.getDealPrice() * req.getPercent());                item.setSalesPrice(item.getSalesPrice() * req.getPercent());            }            Order returnOrder = orderDao.save(order);            log.info("订单号{},方法{},订单总金额{},订单应付金额{},折扣金额{}", order.getId(), "orderDiscount", order.getTotal(), order.getAmount(), order.getDiscount());            List<DiscountOrderItem> list = discountOrderItemDao.findByOrderId(order.getId());            map.put("discountOrderItem", list);            map.put("data", returnOrder);            map.put("result", new Result(200, "折扣成功"));            return map;        });    }    @Override    public Map<String, Object> returnOrder(RemoveZeroReq req) throws Exception {        Order order = orderDao.findOne(req.getOrderId());        CouponInstance couponInstance = couponInstanceDao.findByOrderIdAndStauts(req.getOrderId(), CouponInstanceStatus.NORMAL);        if (couponInstance != null) {            double commission = 0;            Coupon coupon = couponDao.findOne(couponInstance.getCouponId());            for (OrderItem item : order.getItems()) {                if (item.getProductId().equals(couponInstance.getOrderProductId())) {                    item.setDealPrice(item.getDealPrice() + order.getCouponDiscountAmount());                }                commission += item.getCommission();            }            order.relieveCoupon(null, order.getCouponDiscountAmount(), coupon, commission);            couponInstance.setOrderId(null);            couponInstanceDao.save(couponInstance);        }        double amount = 0.0;        Map<String, Object> map = new HashMap<>();        if (order.getStatus().equals(OrderStatus.CANCELED)) {            map.put("result", new Result(400, "订单已取消"));            map.put("data", null);            return map;        }        for (OrderItem item : order.getItems()) {            amount += item.getDealPrice();        }        order.setAmount(amount);        order.setRemoveZero(0.0);        order.setDiscount(Math.rint((order.getTotal() - amount) * 100) / 100d);        orderDao.save(order);        log.info("订单号{},操作{},订单总金额{},订单应付金额{},保存之后的内容{}", order.getId(), "returnOrder", order.getTotal(), amount, order);        List<DiscountOrderItem> list = discountOrderItemDao.findByOrderId(order.getId());        map.put("discountOrderItem", list);        map.put("result", new Result(200, "已成功取消折扣"));        OrderVo orderVo = orderVoCouponInstance(order);        for (OrderVo.OrderItemDto item : orderVo.getItems()) {            Product product = productDao.findOne(item.getProductId());            if (null != item.getSpecs() && item.getSpecs().size() > 0) {                item.setProductSpecs(product.getProductSpecs());            }        }        map.put("data", orderVo);        return map;    }    @Override    public List<EmpCashRes> getEmpCash(String workId) {        WorkShift workShift = shiftDao.findOne(workId);        List<EmpCashRes> emp = new ArrayList<>();        List<Object[]> res = orderDao.getEmpCash(workShift.getStoreId(), workShift.getBeginTime(), new Date());        for (Object[] ob : res) {            if (ob.length == 0) {                return emp;            }            EmpCashRes cashRes = new EmpCashRes();            cashRes.setAmount(Double.parseDouble(ob[0].toString()));            cashRes.setMobile(String.valueOf(ob[1]));            cashRes.setName(String.valueOf(ob[2]));            emp.add(cashRes);        }        return emp;    }    @Override    public Result changeOrderChannel(String orderId, String code, String channel) {        Order order;        if (null != orderId && !"".equals(orderId)) {            order = orderDao.findOne(orderId);        } else {            order = orderDao.findByCode(code);        }        if (order == null) {            return new Result(400, "订单不存在，请核实");        }        Payment payment = paymentDao.findByOrderId(order.getId());        if (payment == null) {            return new Result(400, "无对应的支付信息");        }        order.setChannel(channel);        payment.setChannel(channel);        orderDao.save(order);        paymentDao.save(payment);        return new Result(200, "订单支付方式修改成功");    }    @Override    public List<Map> getStoreSales(String begin, String end, String storeId) throws Exception {        List<Map> list = new ArrayList<>();        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));        Date start = simpleDateFormat.parse(begin);        Date endTime = simpleDateFormat.parse(end);        List<Object[]> objects = orderDao.getStoreSales(storeId, start, endTime);        for (Object[] object : objects) {            Map<String, Object> map = new HashMap<>();            map.put("amount", object[0]);            map.put("date", object[1]);            list.add(map);        }        return list;    }    @Override    public List<Map> getAllStoreSales(String userName, List<StoreVo> storeVos) {        Date start = JodaUtils.getStartOfTodayDateTime();        Date end = JodaUtils.getEndOfTodayDateTime();        List<Map> maps = new ArrayList<>();        ThreadArgumentsBuilder<String, Object> threadBuilder = MapUtils.threadBuilder();        for (StoreVo storeVo : storeVos) {            threadBuilder.put(storeVo.getId(), () -> {                Map map = new HashMap();                double getAmount = leaseProductOrderDao.sumGetAmount(storeVo.getId(), start, end);                double storeSales = orderDao.getAllStoreSales(storeVo.getId(), start, end);                map.put("amount", getAmount + storeSales);                map.put("storeName", storeVo.getName());                map.put("id", storeVo.getId());                List<Integer> status = new ArrayList<>();                status.add(1);                status.add(2);                long count = numDao.countByStatusInAndStoreId(status, storeVo.getId());                long totalCount = numDao.countByStoreId(storeVo.getId());                StoreNumDayCount dayTime = storeNumDayCountDao.findByStoreIdAndDayTime(storeVo.getId(), MyDateUtils.getStartOfToday());                map.put("totalCount", totalCount);                map.put("count", count);                map.put("topCount", null == dayTime ? 0 : dayTime.getQty());                map.put("makeEnabled", storeVo.isMakeEnabled());                map.put("makeEndTime", storeVo.getMakeEndTime());                return map;            });            /*Map map = new HashMap();            double getAmount = leaseProductOrderDao.sumGetAmount(storeVo.getId(), start, end);            double storeSales = orderDao.getAllStoreSales(storeVo.getId(), start, end);            map.put("amount",getAmount+storeSales);            map.put("storeName", storeVo.getName());            map.put("id", storeVo.getId());            List<Integer> status = new ArrayList<>();            status.add(1);            status.add(2);            long count = numDao.countByStatusInAndStoreId(status, storeVo.getId());            long totalCount = numDao.countByStoreId(storeVo.getId());            StoreNumDayCount dayTime = storeNumDayCountDao.findByStoreIdAndDayTime(storeVo.getId(), MyDateUtils.getStartOfToday());            map.put("totalCount", totalCount);            map.put("count", count);            map.put("topCount", null == dayTime ? 0 : dayTime.getQty());            map.put("makeEnabled", storeVo.isMakeEnabled());            map.put("makeEndTime", storeVo.getMakeEndTime());            maps.add(map);*/        }        Map<String, Object> map = threadBuilder.get();        for (StoreVo vo : storeVos) {            maps.add((Map) map.get(vo.getId()));        }        return maps;    }    @Override    public List<CountStoreBillRes> getStoreBill(Date start, Date end, String storeId) {        List<CountStoreBillRes> countStoreBillRes = new ArrayList<>();        if (storeId != null && !storeId.equals("")) {            List<Object[]> amount = orderDao.countOrderBillAmountByStoreId(storeId, start, end);            List<Object[]> onLineAmount = orderDao.countOrderBillOnLineByStoreId(storeId, start, end);            for (Object[] ob : amount) {                CountStoreBillRes res = new CountStoreBillRes();                res.setAmount(Double.valueOf(ob[0].toString()));                res.setCount(Double.valueOf(ob[3].toString()));                res.setStoreName(ob[1].toString());                res.setStoreId(ob[2].toString());                countStoreBillRes.add(res);            }            for (CountStoreBillRes res : countStoreBillRes) {                for (Object[] ob : onLineAmount) {                    if (res.getStoreId().equals(ob[2].toString())) {                        res.setOnLineAmount(res.getOnLineAmount() + Double.valueOf(ob[0].toString()));                    }                }            }        } else {            List<Object[]> amount = orderDao.countOrderBillAmount(start, end);            List<Object[]> onLineAmount = orderDao.countOrderBillOnLine(start, end);            for (Object[] ob : amount) {                CountStoreBillRes res = new CountStoreBillRes();                res.setAmount(Double.valueOf(ob[0].toString()));                res.setCount(Double.valueOf(ob[3].toString()));                res.setStoreName(ob[1].toString());                res.setStoreId(ob[2].toString());                countStoreBillRes.add(res);            }            for (CountStoreBillRes res : countStoreBillRes) {                for (Object[] ob : onLineAmount) {                    if (res.getStoreId().equals(ob[2].toString())) {                        res.setOnLineAmount(res.getOnLineAmount() + Double.valueOf(ob[0].toString()));                    }                }            }        }        return countStoreBillRes;    }    /**     * 获取商品拼接     *     * @param orderItems     * @return     */    private String getMemberProductInfo(List<OrderItem> orderItems) {        StringBuffer stringBuffer = new StringBuffer();        if (orderItems.size() > 0) {            int i = 0;            for (OrderItem orderItem : orderItems) {                i++;                stringBuffer.append(orderItem.getProductName());                stringBuffer.append("× " + orderItem.getQuantity());                if (orderItems.size() != i) {                    stringBuffer.append("，");                }            }        } else {            stringBuffer.append("自定义充值");            stringBuffer.append("× 1");        }        return Stringutil.cutStr(stringBuffer.toString(), 225);    }    /**     * 获取商品拼接     *     * @param orderItems     * @return     */    private String getProductInfo(List<OrderItem> orderItems) {        StringBuffer stringBuffer = new StringBuffer();        int i = 0;        for (OrderItem orderItem : orderItems) {            i++;            stringBuffer.append(orderItem.getProductName());            stringBuffer.append("× " + orderItem.getQuantity());            if (orderItems.size() != i) {                stringBuffer.append("，");            }        }        return Stringutil.cutStr(stringBuffer.toString(), 225);    }    @Autowired    public void setJdbc(JdbcTemplate jdbc) {        this.jdbc = jdbc;    }}